package com.ljfiction.book.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.ljfiction.book.Baner.BookCommentBean;
import com.ljfiction.book.Dialog.IsOrNoDialog;
import com.ljfiction.book.Dialog.NoBackgLodDialog;
import com.ljfiction.book.MyView.DividerItemDecoration;
import com.ljfiction.book.R;
import com.ljfiction.book.activitys.LoginActivity;
import com.ljfiction.book.activitys.MyBookChapterActivity;
import com.ljfiction.book.activitys.OtherfensiActivity;
import com.ljfiction.book.activitys.ShupingDatasActivity;
import com.ljfiction.book.activitys.UserCenterActivity;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.myinterface.MyAuthorMessageInterface;
import com.ljfiction.book.tools.AppUtils;
import com.ljfiction.book.tools.ScreenUtils;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.TimeTool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.BaseRequest;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Android on 2017/9/27.
 */

public class MyBookshupingFragment extends BaseFragment {

    private RecyclerView myshupingrecycler;
private MyAuthorMessageInterface myAuthorMessageInterface;
    private SmartRefreshLayout refreshMyshupingrecycle;
    private String bookId;
    private int page = 1;
    private List<BookCommentBean.DataBean.ListBean> listbean = new ArrayList<>();
    private BookCommentBean bookCommentBean;
    private BaseQuickAdapter mAdapter;
    private Context context;
    private Intent intentShuping;
    private Intent intentImage;
    private IsOrNoDialog isOrNoDialog;
    private LinearLayout nodata;
    private NoBackgLodDialog noBackgLodDialog;
    private boolean isLoddialog=true;
    private LinearLayout onekayread;
    private TextView num;
    private boolean isreadall=false;

    public static MyBookshupingFragment newInstance( String bookid) {
        MyBookshupingFragment newFragment = new MyBookshupingFragment();
        Bundle bundle = new Bundle();
        bundle.putString("booid", bookid);
        newFragment.setArguments(bundle);
        return newFragment;

    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.myauthormessage_fragment, null);
        Bundle args = getArguments();
        if (args != null) {
            this.context = getContext();
            this.bookId = args.getString("booid");
        }
        myshupingrecycler = view.findViewById(R.id.myauthormessage_fragment_recycle);
        refreshMyshupingrecycle = view.findViewById(R.id.myauthormessage_fragment_refresh);
        nodata = view.findViewById(R.id.myauthormessage_fragment_nodata);
        num=view.findViewById(R.id.myauthormessage_fragment_howmuch);
        onekayread=view.findViewById(R.id.myauthormessage_fragment_onekayread);
        intView();
        intData();
        return view;
    }

    private void intData() {
        OkHttpUtils.post(HttpManager.IP + "/comm-getcomminfo")

                .params("id", bookId)
                .params("type", "1")
                .params("startPage", String.valueOf(page))
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        if (isLoddialog&&page==1){
                            if (noBackgLodDialog==null){
                                noBackgLodDialog=new NoBackgLodDialog(context,true);
                            }
                            noBackgLodDialog.show();
                            isLoddialog=false;
                        }
                    }

                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        refreshMyshupingrecycle.finishRefresh();
                        refreshMyshupingrecycle.finishLoadMore();
                        if (noBackgLodDialog!=null){
                            noBackgLodDialog.dismis();
                        }
                        Gson gson = new Gson();
                        try {
                            bookCommentBean = gson.fromJson(s, BookCommentBean.class);
                            if (200 == bookCommentBean.getReturnCode()) {
                                listbean.addAll(bookCommentBean.getData().getList());
                                if (listbean.size() <= 0) {
                                    refreshMyshupingrecycle.setVisibility(View.GONE);
                                    nodata.setVisibility(View.VISIBLE);
                                } else {
                                    refreshMyshupingrecycle.setVisibility(View.VISIBLE);
                                    nodata.setVisibility(View.GONE);
                                }
                                num.setText("共"+bookCommentBean.getData().getTotal()+"条");
                                mAdapter.notifyDataSetChanged();
                            } else {
                                showToast(bookCommentBean.getMsg());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }


                    }
                });
    }

    private void intView() {
        myshupingrecycler.setAdapter(mAdapter = new BaseQuickAdapter<BookCommentBean.DataBean.ListBean, BaseViewHolder>(R.layout.mybookshuping_item, listbean) {
            @Override
            protected void convert(BaseViewHolder helper, BookCommentBean.DataBean.ListBean item) {
                if (item.getCommentisRed()==1||isreadall){
                    helper.getView(R.id.isread).setVisibility(View.VISIBLE);
                    ((CardView) helper.getView(R.id.isreadlayout)).setCardBackgroundColor(Color.parseColor("#F4F4F4"));
                    ((CardView) helper.getView(R.id.isreadlayout)).setCardElevation(0);
                }else {
                    helper.getView(R.id.isread).setVisibility(View.GONE);
                    ((CardView) helper.getView(R.id.isreadlayout)).setCardBackgroundColor(Color.parseColor("#ffffff"));

                }
                helper.setText(R.id.content_mybookshuping, item.getCommentContext())
                        .setText(R.id.mybookshuping_myname, item.getPseudonym())
                        .setText(R.id.mybookshupingbookname, "《" + item.getBookName() + "》")
                        .setText(R.id.mybookshupingtime, TimeTool.getTimeAndChange(String.valueOf(item.getCommentDateTime())))
                        .setText(R.id.selectmybooknum, String.valueOf(item.getThumbsCount()))
                        .setText(R.id.mybookshupingdenglimy, "LV" + item.getUserGrade())
                        .setText(R.id.pinglunmybooknum, String.valueOf(item.getReplyCount()));
                Glide.with(mContext).load(item.getUserHeadPortraitURL()).override(ScreenUtils.getNum(mContext,52), ScreenUtils.getNum(mContext,52)).into((ImageView) helper.getView(R.id.mybookshupingimage));
                if (item.getUserSex() == 0) {
                    ((ImageView) helper.getView(R.id.mybookshupingsex)).setImageResource(R.mipmap.sex_n);
                } else {
                    ((ImageView) helper.getView(R.id.mybookshupingsex)).setImageResource(R.mipmap.sex_v);
                }
                if (item.getVipGrade() > 0) {
                    helper.getView(R.id.isvipimage_mybookshuping).setVisibility(View.VISIBLE);
                } else {
                    helper.getView(R.id.isvipimage_mybookshuping).setVisibility(View.GONE);
                }
                if (item.getIsthumbs() == 1) {
                    ((ImageView) helper.getView(R.id.dianzanmybookimage)).setImageResource(R.mipmap.good);
                } else {
                    ((ImageView) helper.getView(R.id.dianzanmybookimage)).setImageResource(R.mipmap.goodno);
                }
                helper.addOnClickListener(R.id.dianzanmybookimage);
                helper.addOnClickListener(R.id.deletmybookshuping);
                helper.addOnClickListener(R.id.mybookshupingimage);

            }
        });
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                intentShuping = new Intent(context, ShupingDatasActivity.class);
                intentShuping.putExtra("thisshuping", listbean.get(position));
                if (listbean.get(position).getCommentisRed()!=1){
                    myAuthorMessageInterface.todeletCom(listbean.get(position).getId());
                    listbean.get(position).setCommentisRed(1);
                    adapter.notifyDataSetChanged();
                }

                startActivity(intentShuping);
            }
        });
        onekayread.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isreadall){
                    showToast("已全部已读");
                    return;
                }
                myAuthorMessageInterface.todeletCom(2);
                isreadall=true;
                mAdapter.notifyDataSetChanged();
            }
        });
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(final BaseQuickAdapter adapter, View view, final int position) {
                pos = position;
                switch (view.getId()) {
                    case R.id.mybookshupingimage:
                        intentImage = new Intent(context, UserCenterActivity.class);
                        intentImage.putExtra("userId", String.valueOf(listbean.get(position).getUserId()));
                        startActivity(intentImage);
                        break;
                    case R.id.dianzanmybookimage:
                        if (!UserManageBean.isLogin(context)) {
                            return;
                        }
                        OkHttpUtils.post(HttpManager.IP + "/comm-GiveThumbs")

                                .params("commentId", String.valueOf(listbean.get(position).getId()))
                                .execute(new StringCallback() {
                                    @Override
                                    public void onSuccess(String s, Call call, Response response) {
                                        try {
                                            JSONObject jsonObject = new JSONObject(s);
                                            if (jsonObject.getInt("returnCode") == 200) {
                                                if (listbean.get(position).getIsthumbs() == 0) {
                                                    listbean.get(position).setIsthumbs(1);
                                                    listbean.get(position).setThumbsCount(listbean.get(position).getThumbsCount() + 1);
                                                } else {
                                                    listbean.get(position).setIsthumbs(0);
                                                    listbean.get(position).setThumbsCount(listbean.get(position).getThumbsCount() - 1);
                                                }
                                                mAdapter.notifyDataSetChanged();
                                            }else if (jsonObject.getInt("returnCode") == 400){
                                                Intent intent=new Intent(context, LoginActivity.class);
                                                startActivity(intent);
                                                showToast(jsonObject.getString("msg"));
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }

                                    }
                                });
                        break;
                    case R.id.deletmybookshuping:
                        if (popupWindow != null && !popupWindow.isShowing()) {
                            if (pos == 0 && listbean.get(pos).getIsTo() == 1) {
                                zhiding.setText("取消置顶");
                            }else {
                                zhiding.setText("置顶");
                            }
                            popupWindow.showAsDropDown(view);
                        } else {
                            showPopuWindow(view);
                        }
                        break;
                }
            }
        });
        myshupingrecycler.setLayoutManager(new LinearLayoutManager(context));
        refreshMyshupingrecycle.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                page++;
                intData();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                listbean.clear();
                intData();
            }
        });

    }

    private PopupWindow popupWindow;
    private TextView zhiding, shanchu;
    private int pos = 0;
    private int type = 1;//0是取消置顶，1是置顶

    private void showPopuWindow(View view) {
        View contentView = LayoutInflater.from(context).inflate(R.layout.myduanpingpopu, null);
        zhiding = contentView.findViewById(R.id.zhidingmybook);
        shanchu = contentView.findViewById(R.id.deletmybook);
        if (pos == 0 && listbean.get(pos).getIsTo() == 1) {
            zhiding.setText("取消置顶");
        }
        zhiding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (pos == 0 && listbean.get(pos).getIsTo() == 1) {
                    isOrNoDialog = new IsOrNoDialog(context, "确定取消这条评论的置顶？", true);
                    type = 0;
                } else {
                    isOrNoDialog = new IsOrNoDialog(context, "确定置顶这条评论？", true);
                    type = 1;
                }

                isOrNoDialog.setListener(new IsOrNoDialog.Listener() {
                    @Override
                    public void okClick() {
                        OkHttpUtils.get(HttpManager.IP + "/comm-isTop/" + listbean.get(pos).getId() + "/"+bookId+"/"+ type)

                                .execute(new StringCallback() {
                                    @Override
                                    public void onSuccess(String s, Call call, Response response) {
                                        try {
                                            JSONObject jsonObject = new JSONObject(s);
                                            if (jsonObject.getInt("returnCode") == 200) {
                                                popupWindow.dismiss();
                                                page = 1;
                                                listbean.clear();
                                                intData();
                                            }
                                            showToast(jsonObject.getString("msg"));
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                    }

                    @Override
                    public void closeClick() {

                    }
                });
            }
        });

        shanchu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isOrNoDialog = new IsOrNoDialog(context, "确定删除这条评论？", true);
                isOrNoDialog.setListener(new IsOrNoDialog.Listener() {
                    @Override
                    public void okClick() {
                        OkHttpUtils.post(HttpManager.IP + "/comm-delcomminfo")

                                .params("id", String.valueOf(listbean.get(pos).getId()))
                                .params("type", "0")
                                .execute(new StringCallback() {
                                    @Override
                                    public void onSuccess(String s, Call call, Response response) {
                                        try {
                                            JSONObject jsonObject = new JSONObject(s);
                                            if (jsonObject.getInt("returnCode") == 200) {
                                                listbean.remove(pos);
                                                popupWindow.dismiss();
                                                mAdapter.notifyDataSetChanged();
                                            }
                                            showToast(jsonObject.getString("msg"));
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                });
                    }

                    @Override
                    public void closeClick() {

                    }
                });
            }
        });
        popupWindow = new PopupWindow(contentView);
        //使其聚集
        popupWindow.setFocusable(true);
        // 设置允许在外点击消失
        popupWindow.setOutsideTouchable(true);
        //这个是为了点击“返回Back”也能使其消失，并且并不会影响背景
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        // 设置SelectPicPopupWindow弹出窗体的宽
        popupWindow.setWidth(ScreenUtils.getScreenWidth() / 4);
        popupWindow.setHeight(ScreenUtils.getScreenHeight() /7);
        // 设置SelectPicPopupWindow弹出窗体动画效果
        // popupWindow.setAnimationStyle(R.style.AnimBottom);
        //popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.back_search_img));
        popupWindow.showAsDropDown(view);
    }
public  MyBookshupingFragment setLisener(MyAuthorMessageInterface myAuthorMessageInterface){
        this.myAuthorMessageInterface=myAuthorMessageInterface;
        return this;
}
}
